package algotithm.leetcode.bytedance.test560;

import java.util.HashMap;

/**
 * @author zhouyanxiang
 * @Date 2021-03-2021/3/9-21:25
 * @URL https://leetcode-cn.com/problems/subarray-sum-equals-k/
 * @Title 560. 和为K的子数组
 */
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {1,2,3};
        int k = 3;
        int sum = solution.subArraySum(nums, k);
        System.out.println(sum);
    }

    public int subArraySum(int[] nums,int k) {
        int count = 0;
        int pre = 0;
        HashMap<Integer,Integer> map = new HashMap<>(1000);
        map.put(0,1);
        for (int i = 0; i < nums.length; i++) {
            pre += nums[i];
            if (map.containsKey(pre - k)) {
                count += map.get(pre - k);
            }
            map.put(pre,map.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
}
